package DBLayer;
import model.*;

import java.sql.*;

public class DBSupplier {

	private  Connection con;
	
	public DBSupplier() {
		con = DBConnection.getInstance().getDBcon();
	}
	
	public Supplier findSupplier(int ID) {
	 	String wClause = " supID = '" + ID + "'";
	 	return singleWhere(wClause);
	}
	
	private Supplier singleWhere(String wClause) {	
		ResultSet results;
	   	Supplier supObj = new Supplier();
	  	String query =  buildQuery(wClause);
	  	System.out.println("DBSupplier -singelWhere " + query); 
	  	try { // read from project
	    	Statement stmt = con.createStatement();
	       	stmt.setQueryTimeout(5);
	      	results = stmt.executeQuery(query);

	     	if( results.next() ){
	     		supObj = buildSupplier(results); 
	      	}
	        stmt.close();
		}
	  	catch(Exception e){
	    	System.out.println("Query exception - select project : "+e);
	      	e.printStackTrace();
	  	}
		return supObj;
	}
	
	private Supplier buildSupplier(ResultSet results) {
		Supplier supObj = new Supplier();
		DBContactPerson dbcp = new DBContactPerson();
		try {
			supObj.setID(results.getInt("supID"));
	       	supObj.setCVR(results.getString("supCVR"));
	       	supObj.setName(results.getString("supName"));
	       	supObj.setAddress(results.getString("supAddress"));
	       	supObj.setTelephone(results.getString("supTelephone"));
	       	supObj.setEmail(results.getString("supEmail"));
	       	supObj.setContactPerson(dbcp.findContactPerson(results.getInt("conID")));
	       	System.out.println("Dette id laves der en ny contactperson ud fra " + supObj.getContactPerson().getID());
	       	System.out.println("Contactpersons name is " + supObj.getContactPerson().getName());
		}
		catch(Exception e) {
	    	System.out.println("building Supplier object");
	    }
	    return supObj; 
	}
	
	private String buildQuery(String wClause) {
		String query="SELECT supID, supName, supCVR, supAddress, supTelephone, supEmail, conID FROM supplier";	            
	           
		if (wClause.length()>0) {
			query = query + " where " + wClause;
		}
		return query;
	}
	
	
}  
	    
